package hlhj.fhp.burst.activitys

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.Toast
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.tenma.ventures.base.TMActivity
import com.tenma.ventures.bean.utils.TMSharedPUtil
import hlhj.fhp.burst.Contents
import hlhj.fhp.burst.GlideUtil
import hlhj.fhp.burst.R
import hlhj.fhp.burst.TimeUtils
import hlhj.fhp.burst.adapter.FullyGridLayoutManager
import hlhj.fhp.burst.adapter.NineGridAdp
import hlhj.fhp.burst.bean.BaseBean
import hlhj.fhp.burst.bean.BurstListBean
import hlhj.fhp.burst.bean.DetailBean
import hlhj.fhp.burst.bean.MyBurstBean
import hlhj.fhp.burst.customView.LoadingDialog
import hlhj.fhp.burst.ninegrid.ImageInfo
import hlhj.fhp.burst.ninegrid.preview.NineGridViewClickAdapter
import kotlinx.android.synthetic.main.activity_burst_detail_aty.*
import kotlinx.android.synthetic.main.activity_preview_burst.*
import kotlinx.android.synthetic.main.detail_head.view.*
import kotlin.collections.ArrayList

class BurstDetailAty : TMActivity() {
    private var page=1;
    private lateinit var headView:View
    private val datas=ArrayList<DetailBean.DataBean.CommentBean>()
    private lateinit var loadingDialog:LoadingDialog
    private var bid=""
    private var cid=""
    private var icon=""
    private var nineAdp:NineGridAdp?=null
    private val nineDatas=ArrayList<String>()
    private lateinit var adp:BaseQuickAdapter<DetailBean.DataBean.CommentBean,BaseViewHolder>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_burst_detail_aty)
        if (null!=TMSharedPUtil.getTMThemeColor(this)&&TMSharedPUtil.getTMThemeColor(this).length>0){
            loTittle.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this)))
        }
        loadingDialog= LoadingDialog(this)
        val type = intent.getStringExtra("type")//1外 2我的
        headView=LayoutInflater.from(this).inflate(R.layout.detail_head,null)
        initRecy()
        if (intent.getStringExtra("icon")!=null){
            icon=intent.getStringExtra("icon")
        }
        nineAdp=NineGridAdp(nineDatas)
        headView.nineRcy.layoutManager=FullyGridLayoutManager(this,3)
        headView.nineRcy.adapter=nineAdp
        when(type){
            "1"->{
                val listBean = intent.getSerializableExtra("bean") as BurstListBean.DataBean.ListBean
                bid=intent.getIntExtra("id",0).toString()
                Glide.with(this).load(Contents.PUBLICK_URL+icon.replace("\\","/"))
                        .apply(GlideUtil.loadHeadOption())
                        .into(headView.userIcon)
                if (intent.getStringExtra("nickName")==null||intent.getStringExtra("nickName").isEmpty()){
                    headView.userName.text=intent.getStringExtra("memberName")
                }else{
                    headView.userName.text=intent.getStringExtra("nickName")
                }
                headView.tvHowLong.text=intent.getStringExtra("time")
                headView.tvContent.text=intent.getStringExtra("content")

                if (listBean.source_type==1){
                    nineDatas.clear()
                    nineDatas.addAll(listBean.source)
                    nineAdp?.notifyDataSetChanged()

                    val imgs=ArrayList<ImageInfo>()
                    for (i in 0..listBean.source.size-1){
                        val imageInfo = ImageInfo()
                        imageInfo.bigImageUrl=Contents.PUBLICK_URL+listBean.source[i]
                        imageInfo.thumbnailUrl=Contents.PUBLICK_URL+listBean.source[i]
                        imgs.add(imageInfo)
                    }
                    headView.nineGrideView?.setAdapter(NineGridViewClickAdapter(this, imgs))
                }else if (listBean.source_type==2){
                    headView.thumbLo?.visibility=View.VISIBLE
                    headView.nineRcy?.visibility=View.GONE
                    headView.thumbLo.setOnClickListener {
                        val intent = Intent(this, VideoPlayAty::class.java)
                        intent.putExtra("url",listBean.source[0])
                        intent.putExtra("img",Contents.PUBLICK_URL+listBean.video_thumb)
                        startActivity(intent)
                    }
                    Glide.with(this).load(Contents.PUBLICK_URL+listBean.video_thumb).into(headView.imgThumb!!)
                }
                getData(bid)
            }
            "2"->{
                val listBean = intent.getSerializableExtra("bean") as BurstListBean.DataBean.ListBean
                Glide.with(this).load(Contents.PUBLICK_URL+icon.replace("\\","/"))
                        .apply(GlideUtil.loadHeadOption())
                        .into(headView.userIcon)
                headView.userName.text=intent.getStringExtra("nickName")
                headView.tvHowLong.text=intent.getStringExtra("time")
                headView.tvContent.text=intent.getStringExtra("content")
                bid=intent.getIntExtra("id",0).toString()

                getData(bid)
            }
        }
        initListener()



    }

    private fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        btComment.setOnClickListener {
            etContent.setFocusable(true);
            etContent.setFocusableInTouchMode(true);
            etContent.requestFocus();
            val inputManager = etContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(etContent,0)
            cid="0"

        }

        btSend.setOnClickListener {
            OkGo.get<String>(Contents.PUBLICK_URL+Contents.COMMENT)
                    .params("token",TMSharedPUtil.getTMToken(this@BurstDetailAty))
                    .params("burst_id",bid)
                    .params("content",etContent.text.toString())
                    .params("comment_id",cid)
                    .execute(object :StringCallback(){
                        override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                            super.onStart(request)
                            loadingDialog.show()
                        }
                        override fun onSuccess(response: Response<String>?) {
                            loadingDialog.dismiss()
                            val str = response?.body()
                            val bean = Gson().fromJson(str, BaseBean::class.java)
                            if (bean?.code==1){
                                Toast.makeText(this@BurstDetailAty,"评论成功",Toast.LENGTH_SHORT).show()
                                etContent.setText("")
                                datas.clear()
                                getData(bid)
                            }else if (bean?.code==500){
                                GoLoginDialog(this@BurstDetailAty).show()
                            }
                        }
                    })
        }
    }

    private fun initRecy() {
        adp=object :BaseQuickAdapter<DetailBean.DataBean.CommentBean,BaseViewHolder>(R.layout.comment_detail_item,datas){
            override fun convert(helper: BaseViewHolder?, item: DetailBean.DataBean.CommentBean?) {
                Glide.with(mContext).load(Contents.PUBLICK_URL+item?.head_pic?.replace("\\","/"))
                        .apply(GlideUtil.loadHeadOption())
                        .into(helper?.getView(R.id.userIcon)!!)
                GlideUtil.loadImg(mContext,item?.head_pic?.replace("\\","/"),helper?.getView(R.id.userIcon))
                if (null==item?.member_nickname||item?.member_nickname?.isEmpty()!!){
                    helper?.setText(R.id.userName,item?.user_nickname)
                }else{
                    helper?.setText(R.id.userName,item?.user_nickname)
                }
                helper?.setText(R.id.tvContent,item?.content)
                val btlo = helper?.getView<LinearLayout>(R.id.lo)

                btlo?.setOnClickListener {
                    etContent.setFocusable(true);
                    etContent.setFocusableInTouchMode(true);
                    etContent.requestFocus();
                    val inputManager = etContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    inputManager.showSoftInput(etContent,0)
                    cid=item?.id.toString()
                }
                helper?.setText(R.id.tvHowLong,TimeUtils.convertTimeToFormat(item?.create_at!!.toLong()))
                if (item?.p_comment==null){
                    helper?.setVisible(R.id.lorep,false)
                }else{
                    helper?.setVisible(R.id.lorep,true)
                    helper?.setText(R.id.name,"@${item?.p_comment.user_nickname}:")
                    helper?.setText(R.id.tvRep,item?.p_comment.content)
                }

            }
        }
        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        adp.addHeaderView(headView)
    }

    private fun getData(bid:String) {
        OkGo.get<String>(Contents.PUBLICK_URL + Contents.DETAIL)
                .params("burst_id", bid)
                .params("page", page)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        loadingDialog.show()
                    }
                    override fun onSuccess(response: Response<String>?) {
                        loadingDialog.dismiss()
                        val str = response?.body()
                        val bean = Gson().fromJson(str, DetailBean::class.java)
                        if (bean?.code==1){
                            datas.addAll(bean?.data.comment)
                            adp.notifyDataSetChanged()
                        }
                    }
                })
    }
}
